package com.sk.weichat.ui.me.wallet;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sk.weichat.R;
import com.sk.weichat.bean.Question;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.me.SmsCodeForIdentifyActivity;
import com.sk.weichat.util.LiveDataBus;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.SelectionFrame;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import okhttp3.Call;


public class IdentifyThroughAnswerQuestionActivity extends BaseActivity implements View.OnClickListener {
    private ImageView ivClear;
    private TextView tvQuestion;
    private EditText edtAnswer;
    private Button btnNext;
    private String type = "";

    //输错5次的错误码
    private final static int Incorrect_Five_Times_Code = 1040314;
    private final static int request_reset_pay_pswd = 3442;
    // private final static String event_sms_identify = "IdentifyThroughAnswerQuestionActivity_event_sms_identify";

//    private final static int request_sms_identify = 9826;
    //private final static int request_sms_identify_again = 5433;

    // private final static String request_alipay_auth_event = "IdentifyThroughAnswerQuestionActivity_request_alipay_auth_event";//支付宝授权
    private final static int request_aliyun_auth = 9087;//填写实名认证信息

    private Question question;

    private String alipayname = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_identify_through_answer_question);

        alipayname = getIntent() != null ? getIntent().getStringExtra("AlipayName") : "";
        TextView tvTitle = findViewById(R.id.tv_title_center);
        //
        tvTitle.setText(getString(R.string.set_identify_question_title));
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        ivClear = findViewById(R.id.iv_clear);
        ivClear.setOnClickListener(this);
        btnNext = findViewById(R.id.btn_next);
        btnNext.setOnClickListener(this);
        tvQuestion = findViewById(R.id.tv_question);
        edtAnswer = findViewById(R.id.edt_answer);
        //获取问题
        getQuestion(coreManager.getSelfStatus().accessToken);
        edtAnswer.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    ivClear.setVisibility(View.VISIBLE);
                    btnNext.setBackgroundResource(R.drawable.shape_corner_26dp_solid_primary);
                    btnNext.setEnabled(true);
                } else {
                    ivClear.setVisibility(View.GONE);
                    btnNext.setBackgroundResource(R.drawable.shape_corner_26_solid_gray_bdc2c8);
                    btnNext.setEnabled(false);
                }
            }
        });

        LiveDataBus.get().with(IdentifyThroughAnswerQuestionActivity.this.hashCode() + "").observe(this, new Observer<Object>() {
            @Override
            public void onChanged(@Nullable Object o) {
//                if (type.equals(AppConstant.SET_PAY_PASSWORD_TYPE_ALIPAY)) {
//                    //通过支付宝设置的支付密码
//                    AlipayAuthActivity.startAlipayAuthActivity(alipayname, request_alipay_auth_event, IdentifyThroughAnswerQuestionActivity.this);
//                } else if (type.equals(AppConstant.SET_PAY_PASSWORD_TYPE_ALIYUN)) {
                //通过实名认证设置的支付密码
                startActivityForResult(new Intent(mContext, VerifyRealNameInfoActivity.class), request_aliyun_auth);
                //}
            }
        });
        //弹出键盘输入
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    private void getQuestion(String access_token) {
        Map<String, String> params = new HashMap<>();
        String language = Locale.getDefault().getLanguage();
        params.put("language", language);
        params.put("access_token", access_token);
        HttpUtils.post().url(coreManager.getConfig().GET_IDENTIFY_QUESTION)
                .params(params)
                .build()
                .execute(new BaseCallback<Question>(Question.class) {
                    @Override
                    public void onResponse(ObjectResult<Question> result) {
                        if (result.getResultCode() == 1) {
                            question = result.getData();
                            //获取问题成功
                            tvQuestion.setText(question.getProblem());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    private void postAnswerForIdentify(String problemBaseId, String answer, String access_token) {
        Map<String, String> params = new HashMap<>();
        String language = Locale.getDefault().getLanguage();
        params.put("problemBaseId", problemBaseId);
        params.put("answer", answer);
        params.put("access_token", access_token);
        HttpUtils.post().url(coreManager.getConfig().POST_IDENTIFY_QUESTION)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {
                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        if (result.getResultCode() == 1) {
                            //验证成功
                            startActivityForResult(new Intent(mContext, ResetPayPwdNewActivity.class), request_reset_pay_pswd);
                        } else if (result.getResultCode() == Incorrect_Five_Times_Code) {
                            failedMsg = result.getResultMsg();
                            //回答错误达到5次
                            setupIncorrectDialog();
                            selectionFrame.show();
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == request_reset_pay_pswd && resultCode == Activity.RESULT_OK) {
            finish();
        }
        if (requestCode == request_aliyun_auth && resultCode == Activity.RESULT_OK) {
            finish();
        }
    }

    SelectionFrame selectionFrame;
    String failedMsg = "";


    private void setupIncorrectDialog() {
        selectionFrame = new SelectionFrame(this);
        selectionFrame.setSomething(null, failedMsg, getResources().getString(R.string.cancel), getResources().getString(R.string.find_pwsd), new SelectionFrame.OnSelectionFrameClickListener() {
            boolean flag = true;

            @Override
            public void cancelClick() {
                selectionFrame.dismiss();
            }

            @Override
            public void confirmClick() {
                if (flag) {
                    flag = false;
                    //获取用户设置密码的方式
                    //找回密码
                    SmsCodeForIdentifyActivity.startSmsCodeForIdentifyActivity(IdentifyThroughAnswerQuestionActivity.this.hashCode() + "", mContext);
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(String str) {
        if (str.equals("set_question")) {
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.iv_clear:
                edtAnswer.setText("");
                break;
            case R.id.btn_next:
                //验证问题
                postAnswerForIdentify(question.getId(), edtAnswer.getText().toString(), coreManager.getSelfStatus().accessToken);
                break;
        }
    }

}
